import React, {Component} from 'react'
import AlloyTouch from 'AlloyTouch';
import {
    Flex,
    Icon
} from 'antd-mobile';
//let alloytouch = require("alloytouch");
import Transform from 'css3transform';
import diamond from '../../assets/img/diamond.svg'
import { connect } from 'dva';
import { list_view, pull_refresh, foot_div } from './MyListView.less';

class MyListView extends Component {
    constructor(props) {
        super(props);
        this.state = {
            refreshing:false,
            refreshHeight:0,
            loading:false
        };
        this.scrollTarget=null;
       // this.handleScroll = this.throttle(this.changeScroll, 100);
    }

    preDF=(e)=>{
        e.preventDefault();
    }

    componentWillUnmount(){
        console.log(1);
        let supportsPassive = false;
        try {
            let opts = Object.defineProperty({}, 'passive', {
                get: function() {
                    supportsPassive = true;
                }
            });
            window.addEventListener("test", null, opts);
        } catch (e) {}
        document.removeEventListener("touchmove", this.preDF ,supportsPassive ? { passive: false } : false);
        this.scrollTarget=null;
    }

    refresh = (th) =>{
        this.setState({
            refreshing:true,
            loading:true
        },()=>{
             this.props.refresh().then((r)=>{
              //   if(r&&r.r==true){
                     this.setState({
                         refreshing:false,
                         refreshHeight:0,
                         loading:false
                     });
                     th.to(0);
                 // }else {
                 //     this.setState({
                 //         refreshing:false,
                 //         refreshHeight:0,
                 //         loading:false
                 //     });
                 // }
             })
        });
    }

    componentDidMount() {
        const than =this;
        Transform(this.targetName,true);
        // let target = document.querySelector("#scroller");
        //Transform(target,true);
        console.log(this.state);
        this.scrollTarget= new AlloyTouch({
            touch:`#wrapperScrollUseMy${this.props.kid}`,//反馈触摸的dom
            target: this.targetName, //运动的对象
            // property: "translateY",  //被运动的属性
            min: -1000000, //不必需,运动属性的最小值,越界会回弹
            //  max: 0, //不必需,滚动属性的最大值,越界会回弹
            // vertical: true,//不必需，默认是true代表监听竖直方向touch
            sensitivity: 1,//不必需,触摸区域的灵敏度，默认值为1，可以为负数
            factor: 1,//不必需,表示触摸位移与被运动属性映射关系，默认值是1
            // step: 45,//不必需，用于校正到step的整数倍
            // preventDefault:document.getElementById(`#wrapperScrollUseMy${this.props.kid}`),
            change:(e,value)=>{

                 if( e > 0 ){
                     this.setState({
                         refreshHeight:e
                     })
                 };
                let wrap = document.getElementById(`wrapperScrollUseMy${this.props.kid}`);
                if(this.targetName!=undefined){

                    if(parseFloat(wrap.offsetHeight) >= parseFloat(this.targetName.offsetHeight) && this.scrollTarget.min!=0){
                        //   console.log(1);
                        this.scrollTarget.min=0;
                    }else if(parseFloat(wrap.offsetHeight) < parseFloat(this.targetName.offsetHeight)){
                        let sch = parseFloat(wrap.offsetHeight)-parseFloat(this.targetName.offsetHeight);
                        if(this.scrollTarget.min!=sch){
                            this.scrollTarget.min=parseFloat(wrap.offsetHeight)-parseFloat(this.targetName.offsetHeight);
                        }
                    }
                }
                 // alert(1);
               // console.log(e);
                if (this.scrollTarget!==null&&e <= this.scrollTarget.min + wrap.offsetHeight && this.state.loading==false && this.props.hasMore==true) {
                    this.setState({
                        loading:true
                    });
                    this.props.loadMore().then((r)=>{
                        if(r.r==true){
                            this.setState({
                                loading:false
                            })
                        }
                    });
                }
            }, //不必需，属性改变的回调。alloytouch.css版本不支持该事件
            touchStart:(e,value)=>{
                //console.log(scrollTarget.min);

                //  scrollTarget.min=parseFloat(window.innerHeight)-bottomHeight-parseFloat(this.targetName.offsetHeight);
                //  console.log(scrollTarget.min);
            },
            touchMove:(e,value)=>{
                // scrollTarget.min=parseFloat(window.innerHeight)-bottomHeight-parseFloat(this.targetName.offsetHeight);
               // if(value<this.scrollTarget.min){
                    // this.scrollTarget.to(parseFloat(window.innerHeight)-parseFloat(this.targetName.offsetHeight), 600);
               // }
                //   console.log(this.to);
                //  this.to(window.innerHeight-bottomHeight-this.target.offsetHeight, 100);
            },
            touchEnd: function (evt, value) {
                if (value > 70) {
                    this.to(60);
                    than.refresh(this);
                    return false;
                }
            },
            // animationEnd:function(value){  } //运动结束
            property: "translateY",  //被滚动的属性
            //  sensitivity: 1,//不必需,触摸区域的灵敏度，默认值为1，可以为负数
            // factor: 1,//不必需,默认值是1代表touch区域的1px的对应target.y的1
            //  min: - 3000, //不必需,滚动属性的最小值
            max: 0, //不必需,滚动属性的最大值
            step: 50,
            animationEnd: function (value) {
                //   console.log(this.to);
                // this.to(window.innerHeight-bottomHeight-this.target.offsetHeight, 100);
                //console.log(value);
            },
            pressMove: function (value) {


                //   console.log(scrollTarget.min);
                // scrollTarget.min=window.innerHeight-bottomHeight-this.targetName.offsetHeight;

            },
            bindSelf:true
        });

        let supportsPassive = false;
        try {
            let opts = Object.defineProperty({}, 'passive', {
                get: function() {
                    supportsPassive = true;
                }
            });
            window.addEventListener("test", null, opts);
        } catch (e) {}

        this.props.getAlloyTouch(this.scrollTarget);
        document.addEventListener("touchmove", this.preDF, supportsPassive ? { passive: false } : false);
      //  this.changeScroll(0);
    }

    render() {
        const { className='', style, data=[], renderItem, hasMore,cc, itemWrapperClass, bo, bottomStyle={} } = this.props;
        let { refreshHeight, refreshing, loading } = this.state;
      //  console.log(refreshHeight,refreshing);
        return (
                <div

                    id={`wrapperScrollUseMy${this.props.kid}`}
                    className={ `${className} ${list_view}` }
                    style={style}
                >
                    {/* <Flex justify="center" align="center" style={{ height: refreshHeight + 'px' }} className={ pull_refresh } ref={ (node)=>{this.refreshDom=node} }>
                         <img
                             className={ refreshHeight > 70 ? "imgup" :"" }
                             style={{  height: refreshHeight*0.6 + 'px' }}
                             src={ refreshing==true ? require("../../assets/img/loading.gif") : require("../../assets/img/arrow.png")}
                         />
                    </Flex> */}
                    <div id={`ScrollUseMy${this.props.kid}`} ref={ref=>this.targetName=ref}>
                        <div className={ itemWrapperClass } style={cc?{marginBottom:"3rem"}:bo?{marginBottom:"1rem"}:{}}>
                            {  data.map(renderItem) }
                        </div>
                        <div className="Mlv_bottom" style={ bottomStyle }>
                            {/*{*/}
                                {/*loading == true ? <Flex justify="center" style={{ borderTop:"0.01rem solid #999" }}>*/}
                                                       {/*<img style={{ height:'0.8rem' }} src={ require("../../assets/img/loading.gif") } />*/}
                                                   {/*</Flex> : <div></div>*/}
                            {/*}*/}
                            {
                                hasMore == false ?
                                    <div className={ foot_div }>
                                        {/* 没有更多了 */}
                                        <span><span><Icon style={{display: 'block', width: '.24rem', height: '.24rem', position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)'}} type={ diamond.id }/></span></span>
                                    </div>
                                    : ""
                            }
                        </div>
                    </div>
                </div>
        )
    }
}

MyListView.defaultProps = {
    getAlloyTouch: () => {},
    renderItem: ()=>{},
    refresh: ()=>{
        return new Promise(function(resolve, reject) {
           // setTimeout(function() {
                resolve(true);
              //  console.log(1)
         //   }, 2000);
        })
    },
    loadMore:() => {
        return new Promise(function(resolve, reject) {
            // setTimeout(function() {
            resolve({ r:true});
            //  console.log(1)
            //   }, 2000);
        })
    }
};

export default connect(({ app }) => ({ app }))(MyListView);

/*
 * 长列表组件，集合刷新和下载加载共能，例子可以看搜素页
 * */
